package com.coszero.utils.app

import android.content.Context
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.net.ConnectivityManager
import android.os.Build
import android.text.Html
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.InputStream
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.text.DecimalFormat

/**
 * <pre>
 * author: Blankj
 * blog  : http://blankj.com
 * time  : 2016/08/02
 * @link(https://github.com/Blankj/AndroidUtilCode/edit/master/utilcode/src/main/java/com/blankj/utilcode/util/AppUtils.java)
 * desc  : App工具类，获取app信息，和操作app-比如安装和自动卸载等
</pre> *
 *
 * @version 1
 */
class AppUtils private constructor() {
    init {
        throw UnsupportedOperationException("cannot be instantiated")
    }

    companion object {
        /**
         * 设置textView图标
         *
         * @param drawable
         * @param textView
         */
        fun setLeftIcon(drawable: Drawable?, textView: TextView) {
            drawable?.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
            textView.setCompoundDrawables(drawable, null, null, null)
        }

        /**
         * 默认的密码字符串组合，用来将字节转换成 16 进制表示的字符
         */
        protected var hexDigits: CharArray = charArrayOf(
            '0',
            '1',
            '2',
            '3',
            '4',
            '5',
            '6',
            '7',
            '8',
            '9',
            'a',
            'b',
            'c',
            'd',
            'e',
            'f'
        )
        protected var messagedigest: MessageDigest? = null

        init {
            try {
                messagedigest = MessageDigest.getInstance("MD5")
            } catch (e: NoSuchAlgorithmException) {
                e.printStackTrace()
            }
        }

        @Throws(IOException::class)
        fun getFileMD5String(file: File?): String {
            val fis: InputStream = FileInputStream(file)
            val buffer = ByteArray(1024)
            var numRead = 0
            while ((fis.read(buffer).also { numRead = it }) > 0) {
                messagedigest!!.update(buffer, 0, numRead)
            }
            fis.close()
            return bufferToHex(messagedigest!!.digest())
        }

        fun bufferToHex(bytes: ByteArray): String {
            return bufferToHex(bytes, 0, bytes.size)
        }

        private fun bufferToHex(bytes: ByteArray, m: Int, n: Int): String {
            val stringbuffer = StringBuffer(2 * n)
            val k = m + n
            for (l in m until k) {
                appendHexPair(bytes[l], stringbuffer)
            }
            return stringbuffer.toString()
        }

        private fun appendHexPair(bt: Byte, stringbuffer: StringBuffer) {
            val c0 = hexDigits[(bt.toInt() and 0xf0) shr 4] // 取字节中高 4 位的数字转换
            // 为逻辑右移，将符号位一起右移,此处未发现两种符号有何不同
            val c1 = hexDigits[bt.toInt() and 0xf] // 取字节中低 4 位的数字转换
            stringbuffer.append(c0)
            stringbuffer.append(c1)
        }


        //end
        fun getChannelName(context: Context?): String? {
            if (context == null) {
                return null
            }
            var channelName = "qutuo"
            try {
                val packageManager = context.packageManager
                if (packageManager != null) {
                    //注意此处为ApplicationInfo 而不是 ActivityInfo,因为友盟设置的meta-data是在application标签中，而不是某activity标签中，所以用ApplicationInfo
                    val applicationInfo = packageManager.getApplicationInfo(context.packageName, android.content.pm.PackageManager.GET_META_DATA)
                    if (applicationInfo != null) {
                        if (applicationInfo.metaData != null) {
                            channelName = applicationInfo.metaData["UMENG_CHANNEL"].toString()
                        }
                    }
                }
            } catch (e: PackageManager.NameNotFoundException) {
                e.printStackTrace()
            }
            return channelName
        }

        /**
         * 判断是否联网
         *
         * @return
         */
        fun isNetworkConnected(context: Context): Boolean {
            val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val network = cm.activeNetworkInfo
            if (network != null) {
                return network.isAvailable
            }
            return false
        }

        /**
         * 设置textView图标
         *
         * @param drawable
         * @param textView
         */
        fun setRightIcon(drawable: Drawable, textView: TextView) {
            drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
            textView.setCompoundDrawables(null, null, drawable, null)
        }

        @JvmStatic
        fun setTopIcon(drawable: Drawable, textView: TextView) {
            drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
            textView.setCompoundDrawables(null, drawable, null, null)
        }

        /**
         * 隐藏view
         *
         * @param view
         */
        fun hideView(view: View?) {
            if (null == view) {
                return
            }
            if (view.visibility == View.VISIBLE) {
                view.visibility = View.GONE
            }
        }

        /**
         * 显示view
         *
         * @param view
         */
        fun showView(view: View?) {
            if (null == view) {
                return
            }
            if (view.visibility == View.GONE || view.visibility == View.INVISIBLE) {
                view.visibility = View.VISIBLE
            }
        }

        fun inVisibleView(view: View) {
            if (view.visibility == View.VISIBLE) {
                view.visibility = View.INVISIBLE
            }
        }

        /**
         * 改变字符串中间的颜色
         *
         * @param str
         * @param start
         * @param end
         * @param color
         */
        /**
         * 改变部分文字的颜色
         *
         * @param textView 控件
         * @param start 开始文字
         */
        fun changeTextColor(
            context: Context,
            textView: TextView,
            start: Int,
            end: Int,
            colorRes: Int
        ) {
            val s = textView.text.toString()
            val builder = SpannableStringBuilder(s)
            val redSpan = ForegroundColorSpan(context.resources.getColor(colorRes))
            builder.setSpan(redSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            textView.text = builder
        }

        /**
         * @param context
         * @param colorId
         * @return
         */
        @JvmStatic
        @Deprecated("Use {@link ResourceUtils#getColor(android.content.Context, int)}")
        fun getColor(context: Context, colorId: Int): Int {
            return context.resources.getColor(colorId)
        }

        @JvmStatic
        @Deprecated("")
        fun getString(context: Context, strId: Int): String {
            return context.resources.getString(strId)
        }

        /**
         * 拼接图片url，项目专用
         */
        fun imageUrlFormat(urls: List<String>?): String {
            if (urls == null || urls.size == 0) {
                return ""
            }
            val sqlSb = StringBuffer()
            for (url in urls) {
                sqlSb.append("$url,")
            }
            // 去除最后的逗号
            val subSql = sqlSb.substring(0, sqlSb.length - 1)
            return subSql.toString()
        }

        fun double2Str(num: Double): String {
            val format1 = DecimalFormat("0.00")
            val couponMoney = format1.format(num)
            return couponMoney
        }

        fun getDrawable(context: Context, rosId: Int): Drawable {
            return context.resources.getDrawable(rosId)
        }

        /**
         * 按要求格式化文字颜色
         * 输入框字数限制专用
         *
         * @param inputNum 输入的数量
         * @param maxLength 最大数量
         * @return
         */
        fun formatColorText(inputNum: Int, maxLength: Int): Spanned {
            return Html.fromHtml("<font color = '#0000ff'>$inputNum</font><font color = '#999999'>/$maxLength</font>")
        }

        fun strToInt(tag: String): Int {
            if (TextUtils.isEmpty(tag)) {
                return 0
            }
            return try {
                tag.toInt()
            } catch (e: Exception) {
                0
            }
        }

        /**
         * 修改矢量图颜色
         *
         * @param context
         * @param resourceId R.drawable.ic_home_black_24dp
         * @param color getResources().getColor(R.color.color_blue)
         * @param imageView
         * @Link(https://blog.csdn.net/chenkezhenzhe/article/details/70143859)
         */
        fun setSvgColor(context: Context, resourceId: Int, color: Int, imageView: ImageView) {
            val vectorDrawableCompat =
                VectorDrawableCompat.create(context.resources, resourceId, context.theme)
            //你需要改变的颜色
            vectorDrawableCompat!!.setTint(color)
            imageView.setImageDrawable(vectorDrawableCompat)
        }

        /**
         * 检查权限是否被授权
         *
         * @param mContext c
         * @param permission p
         * @return true or false
         */
        fun checkPermission(mContext: Context, permission: String): Boolean {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ContextCompat.checkSelfPermission(
                        mContext,
                        permission
                    ) == PackageManager.PERMISSION_GRANTED
                ) {
                    return true
                }
            }
            return false
        }

        /* * 检查多个权限是否全部被授予
     *
     * @param context    上下文
     * @param permissions 权限字符串数组，例如 Manifest.permission.WRITE_EXTERNAL_STORAGE
     * @return 如果所有权限都被授予返回 true，否则返回 false
     */
        fun checkPermissions(context: Context, permissions: Array<String>): Boolean {
            for (permission in permissions) {
                if (ContextCompat.checkSelfPermission(
                        context,
                        permission
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    return false
                }
            }
            return true
        }
    }
}
